package com.example.demo.entity;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.Serializable;
import java.lang.reflect.Field;

/**
 * Created by Wen Gao on 2018/7/12.
 */
public class BaseEntity implements Comparable, Serializable {

    Logger logger = LogManager.getLogger(this.getClass());

    public String toJson() {
        ObjectMapper mapper = new ObjectMapper();
        String json = "";
        try {
            json =  mapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            logger.error(e);
        }
        return json;
    }

    @Override
    public int compareTo(Object o) {
        return 0;
    }

    @Override
    public boolean equals(Object o) {
        Field[] allFields = o.getClass().getDeclaredFields();
        for(Field field : allFields) {
            try {
                // 有任意一个属性不一致就return false
                field.setAccessible(true);
                if(field.get(o)!=null) {
                    if (!field.get(o).equals(field.get(this))) {
                        System.out.println("Not Equals, because " + field.getName() + " is difference");
                        return false;
                    }
                } else if(field.get(this)==null) {
                    continue;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }
}
